import type { FunctionalComponent } from "vue";
// import type { SetupContext } from 'vue';
import type { RouteRecordRaw } from "vue-router";
import { QCheckbox, QExpansionItem, QItemSection, QList, QItem, Notify } from "quasar";
import { i18n } from "_s/boot/i18n";
import { difference } from "lodash";

import { useMenuHook } from "_s/stores/modules/menu";
const routers = useMenuHook().routers;
const menuList = routers.filter(item => item.children && item.children.length > 0 && !item.meta?.hidden);

// 获取默认id
const getDefaultPath = () => {
  let defaultPathChildren = {} as RouteRecordRaw;
  const defaultRouter = menuList.find(item => item.path === "/");

  if (defaultRouter && defaultRouter.redirect) {
    for (const item of menuList) {
      let parentPath = item.path;
      if (parentPath == "/") {
        parentPath = "";
      }
      if (item.children) {
        for (const temp of item.children) {
          const childrenPath = temp.path;
          const path = parentPath + (childrenPath.startsWith("/") ? "" : "/") + childrenPath;

          if (path === defaultRouter.redirect) {
            defaultPathChildren = temp;
          }
        }
      }
    }
  }
  return defaultPathChildren;
};

export const defaultRoute = getDefaultPath(); // 获取默认路由
export const choiceLimits = ref<string[]>([]); // 选择的菜单
export const routerLimits = ref<RouteRecordRaw>(); // 选择的菜单下的按钮

export const choiceButtons = ref<string[]>([]);

const link = ref<string>("");

if (defaultRoute && defaultRoute.meta && typeof defaultRoute.meta.id === "string") {
  // 默认菜单自动选择
  choiceLimits.value.push(defaultRoute.meta.id);
}

// type FComponentProps = {
//   menus: string[];
//   // choiceButtons: string[];
// };

const createChildren = (children: Required<RouteRecordRaw>[]) => {
  const arr = [];
  for (const temp of children) {
    if (!temp.meta) break;
    const { title, id } = temp.meta;
    const obj = h(
      QItem,
      {
        clickable: true,
        active: link.value == id,
        activeClass: "item_active"
      },
      {
        default: () =>
          h(
            QItemSection,
            {
              class: ["cursor-pointer", "selectable", "q-ml-lg"],
              onClick: () => {
                link.value = id as string;
                routerLimits.value = temp;
                // getrouterLimits(temp)
              }
            },
            {
              default: () =>
                h("div", [
                  h(QCheckbox, {
                    modelValue: choiceLimits.value,
                    val: id,
                    dense: true,
                    "onUpdate:modelValue": (val: string) => {
                      confirmOption(val, temp);
                    }
                  }),
                  h(
                    "span",
                    {
                      class: ["q-ml-md"]
                    },
                    i18n.global.t(title as string)
                  )
                ])
            }
          )
      }
    );
    arr.push(obj);
  }
  return arr;
};

// 函数式组件
export const LimitsHead: FunctionalComponent = () => {
  // choiceButtons.value = props.choiceButtons;
  if (Array.isArray(menuList) && menuList.length > 0) {
    return h(
      QList,
      {
        class: ["rounded-borders"]
      },
      () => {
        const renderArr = [];
        for (const temp of menuList) {
          if (!temp.meta) return;
          const { id, title } = temp.meta;
          if (temp.children && temp.children.length > 1) {
            const obj = h(QExpansionItem, null, {
              header: () =>
                h(QItemSection, null, {
                  default: () => {
                    return [
                      h("div", null, [
                        h(QCheckbox, {
                          modelValue: choiceLimits.value,
                          val: id,
                          dense: true,
                          "onUpdate:modelValue": (val: string) => {
                            confirmOption(val, temp as Required<RouteRecordRaw>);
                          }
                        }),
                        h(
                          "span",
                          {
                            class: ["q-ml-md"]
                          },
                          i18n.global.t(title as string)
                        )
                      ])
                    ];
                  }
                }),
              default: () => createChildren(temp.children as Required<RouteRecordRaw>[])
            });
            renderArr.push(obj);
          } else {
            if (!temp.children) return;
            const children = temp.children[0] as Required<RouteRecordRaw>;
            const obj = h(
              QItem,
              {
                clickable: true,
                active: link.value == children.meta?.id,
                activeClass: "item_active"
              },
              {
                default: () =>
                  h(
                    QItemSection,
                    {
                      class: ["cursor-pointer", "selectable"],
                      onClick: () => {
                        link.value = children.meta?.id as string;
                        routerLimits.value = temp;
                        // getrouterLimits(temp as Required<RouteRecordRaw>)
                      }
                    },
                    {
                      default: () =>
                        h("div", [
                          h(QCheckbox, {
                            modelValue: choiceLimits.value,
                            val: children.meta?.id,
                            dense: true,
                            "onUpdate:modelValue": (val: string) => {
                              confirmOption(val, children);
                            }
                          }),
                          h(
                            "span",
                            {
                              class: ["q-ml-md"]
                            },
                            i18n.global.t(title as string)
                          )
                        ])
                    }
                  )
              }
            );
            renderArr.push(obj);
          }
        }
        return renderArr;
      }
    );
  }
};

const getChildIds = (route: Required<RouteRecordRaw>) => {
  const { id, type } = route.meta;
  if (type === "module") {
    if (route.children && route.children.length > 0) {
      const childrenIds = route.children.map(item => {
        if (item.meta) {
          addChoiceButtons(item.meta.limits, item.meta.id as string);

          return item.meta.id;
        }
      });
      return childrenIds.concat(id);
    }
  } else {
    const parentId = id!.split("_")[0];
    if (route.meta) {
      addChoiceButtons(route.meta.limits, id!);
    }
    // addChoiceButtons(item.meta.limits as string[])
    return [parentId, id];
  }
};

const confirmOption = (value: string, route: Required<RouteRecordRaw>) => {
  // const meta = route.meta;
  // const { id, type } = meta;
  const oldLimits = JSON.parse(JSON.stringify(choiceLimits.value));

  const diffLimits = difference(oldLimits, value); // 取消选择的值
  console.log("diffLimits", diffLimits);
  if (diffLimits.length > 0) {
    console.log("defaultRoute", defaultRoute);
    // 取消选择
    if (defaultRoute && defaultRoute.meta) {
      if (diffLimits.includes(defaultRoute.meta.id!)) {
        return Notify.create({ type: "error", message: i18n.global.t(defaultRoute.meta.title!) + ` 必须选择` });
      }
    }
    deleteLimits(diffLimits, route);
  } else {
    // 选择

    // const ids = getChildIds(route) as string[];

    choiceLimits.value = Array.from(new Set([...choiceLimits.value, ...(getChildIds(route) as string[])]));
  }
};

const deleteLimits = (diffLimits: string[], route: Required<RouteRecordRaw>) => {
  const { id, type } = route.meta;
  const oldLimits = JSON.parse(JSON.stringify(choiceLimits.value));
  if (type === "module") {
    if (route.children && route.children.length > 0) {
      const childrenIds = route.children.map(item => {
        if (item.meta) {
          delChoiceButtons(item.meta.id!);
          return item.meta.id;
        }
      });
      // delChoiceButtons(childrenIds as string[],item.meta.id); // 删除与菜单相关的按钮权限
      const newDiffLimits = diffLimits.concat(childrenIds as string[]);
      const diffNewDiffLimits = difference(oldLimits, newDiffLimits); // 取消选择的值
      choiceLimits.value = diffNewDiffLimits;
    }
    // 获取子集id
  }
  if (type === "page") {
    delChoiceButtons(id!); // 删除与菜单相关的按钮权限
    // 获取父id
    const parentId = id!.split("_")[0];
    let length = 0;
    for (const temp of oldLimits) {
      if (temp.includes(parentId)) {
        length++;
        if (length > 2) break;
      }
    }
    if (length > 2) {
      choiceLimits.value = oldLimits.filter((item: string) => item !== id!);
    } else {
      const filterLimits = oldLimits.filter((item: string) => item.indexOf(parentId!) === -1);
      choiceLimits.value = filterLimits;
    }
  }
};

const delChoiceButtons = (routerId: string) => {
  choiceButtons.value = choiceButtons.value.filter(item => !item.includes(routerId));
};

const addChoiceButtons = (ids: string[] | undefined, routerId: string) => {
  if (ids && ids.length > 0) {
    for (const id of ids) {
      choiceButtons.value.push(routerId + "_" + id);
    }
  }
};
